package com.tc.rocketmq.basic;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * @Auther: tianchao
 * @Date: 2021/9/4 21:49
 * @Description:
 */
@Slf4j
@Component
public class SpringProducer {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     *
     * @param topic testbootTopic
     * @param message
     */
    public void sendMessage(String topic,String message){
        this.rocketMQTemplate.convertAndSend(topic, message);
    }

    /**
     *
     * @param topic testbootTranTopic
     * @param msg
     */
    public void sendMessageInTransaction(String topic,String msg){
        String[] tags = new String[] {"TagA", "TagB", "TagC", "TagD", "TagE"};
        for (int i = 4; i < 5; i++) {
            Message<String> message = MessageBuilder.withPayload(msg)
                    .setHeader(RocketMQHeaders.TRANSACTION_ID, "TransID_" + i)
                    .setHeader(RocketMQHeaders.TAGS, tags[i % tags.length])
                    .setHeader("MyProp", "MyProp_" + i)
                    .build();
            String destination = topic + ":" + tags[i%tags.length];
            // In sendMessageInTransaction(), the first parameter transaction name ("test")
            // must be same with the @RocketMQTransactionListener's member field 'transName'
            SendResult sendResult = rocketMQTemplate.sendMessageInTransaction("rocketmq_test_boot_tran",destination,message,null);
            log.info("发送消息： {}",sendResult);
        }
    }
}
